package com.mask.sca.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mask.sca.core.entity.RoleDTO;
import com.mask.sca.core.entity.UserDTO;
import com.mask.sca.core.vo.RegisterParamVo;
import com.mask.sca.member.entity.MemberEntity;
import com.mask.sca.member.mapper.MemberMapper;
import com.mask.sca.member.service.MemberService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author：jian
 * @Package：com.mask.sca.member.service.impl
 * @Project：mask-sca-cloud
 * @name：MemberServiceImpl
 * @Date：2025/7/25 18:08
 * @Filename：MemberServiceImpl
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private PasswordEncoder passwordEncoder;


    @Override
    public UserDTO loadByUsername(String username) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MemberEntity::getPhone,username);
        MemberEntity member = memberMapper.selectOne(queryWrapper);
        if (null != member){
            UserDTO userDTO = new UserDTO();
            userDTO.setId(member.getId());
            userDTO.setUsername(member.getPhone());
            userDTO.setPassword(member.getPassword());
            userDTO.setTenantId("1");
            userDTO.setEnabled(true);
            RoleDTO roleDTO = new RoleDTO();
            roleDTO.setId(1L);
            roleDTO.setTenantId("1");
            roleDTO.setRoleCode("USER");
            roleDTO.setRoleName("会员");
            List<RoleDTO> roles = new ArrayList<>();
            roles.add(roleDTO);
            userDTO.setRoles(roles);
            userDTO.setStatus(member.getStatus());
            return userDTO;
        }else {
            return null;
        }
    }

    @Override
    public void addMember(RegisterParamVo member) {
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setPhone(member.getPhone());
        memberEntity.setUserId(0L);
        memberEntity.setPassword(passwordEncoder.encode(member.getPhone()));
        memberEntity.setEmail(member.getEmail());
        memberEntity.setAvatar(member.getAvatar());
        memberEntity.setStatus(1);
        memberEntity.setMemberNo("MEM"+ new Date().getTime());
        memberEntity.setLevelId(0L);
        memberEntity.setRegisterTime(new Date());
        memberMapper.insert(memberEntity);
    }
}
